package ggy.zzu.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


//创建mybatis工具类
public class MybatisUtil {

    //创建工厂
    private static SqlSessionFactory sessionFactory;

    static {

        //获取资源
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //开始建造
            sessionFactory = new SqlSessionFactoryBuilder().build(is);
            //释放资源
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession对象
    public static SqlSession getSqlsession(){
        return sessionFactory.openSession();
    }

    //释放资源
    public static void close(SqlSession sqlSession){
        if (sqlSession!=null)
        sqlSession.close();
    }
}
